package com.test.udpserver;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.widget.TextView;

import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.MulticastSocket;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

public class MainActivity extends AppCompatActivity {

    private MulticastSocket ds;
    String multicastHost = "224.0.0.1";
//    String multicastHost = "255.255.255.255";
    InetAddress receiveAddress;
    TextView tv;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv = findViewById(R.id.tv);
        try {
//            multicastHost = getBroadcast();
            System.out.println("Broadcast host: " + multicastHost);
            ds = new MulticastSocket(2054);
            InetAddress receiveAddress = InetAddress.getByName(multicastHost);
            ds.joinGroup(receiveAddress);
            new Thread(new Runnable() {
                @Override
                public void run() {

                    // TODO Auto-generated method stub
                    byte buf[] = new byte[1024];
                    final DatagramPacket dp = new DatagramPacket(buf, 1024);
                    while (true) {
                        try {
                            ds.receive(dp);
                            //Toast.makeText(this, new String(buf, 0, dp.getLength()), Toast.LENGTH_LONG);
//                            System.out.println("client ip : "+new String(buf, 0, dp.getLength()));
//                            System.out.println(dp.getAddress());
                            final String ip = dp.getAddress().toString();
                            tv.post(new Runnable() {
                                @Override
                                public void run() {
                                    String content = tv.getText().toString();
                                    content += "\n" + ip + " 上线了！";
                                    tv.setText(content);
                                }
                            });
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }).start();
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }


    }

    public static String getBroadcast() throws SocketException {
        System.setProperty("java.net.preferIPv4Stack", "true");
        for (Enumeration<NetworkInterface> niEnum = NetworkInterface.getNetworkInterfaces(); niEnum.hasMoreElements(); ) {
            NetworkInterface ni = niEnum.nextElement();
            if (!ni.isLoopback()) {
                for (InterfaceAddress interfaceAddress : ni.getInterfaceAddresses()) {
                    if (interfaceAddress.getBroadcast() != null) {
                        return interfaceAddress.getBroadcast().toString().substring(1);
                    }
                }
            }
        }
        return null;
    }
}
